<template>
  <el-dialog
    :visible.sync="show"
    width="600px"
    top="10vh"
    :before-close="beforeClose"
    :close-on-click-modal="false"
  >
    <template #title>
      <h2 style="margin: 0; color: #333">{{ isEdit ? '修改角色' : '添加角色' }}</h2>
    </template>
    <el-form
      :model="formData"
      :rules="rules"
      ref="formRef"
      label-width="80px"
      size="medium"
      :before-close="beforeClose"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="formData.roleName" placeholder="请输入角色名称，如：管理员"></el-input>
      </el-form-item>

      <el-form-item label="角色描述" prop="description">
        <el-input
          type="textarea"
          v-model="formData.description"
          placeholder="请输入角色描述，如：负责管理、监督和维护系统"
          rows="3"
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" style="padding-right: 10px">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addRoleApi, updateRoleApi } from '@/api/role'
export default {
  props: {
    show: {
      type: Boolean,
      default: false
    },
    editRow: {
      type: Object,
      default: () => ({})
    }
  },
  computed: {
    isEdit() {
      return !!this.editRow.roleId
    }
  },
  watch: {
    show(value) {
      if (value && this.editRow.roleId) {
        this.formData = { ...this.editRow }
      }
    }
  },
  data() {
    return {
      rules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        description: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
      },
      formData: {
        roleId: null,
        roleName: '',
        description: ''
      }
    }
  },
  methods: {
    // 提交表单
    submitForm() {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          let res
          if (this.isEdit) {
            res = await updateRoleApi(this.formData)
          } else {
            res = await addRoleApi(this.formData)
          }
          if (res.success) {
            this.$message.success(this.isEdit ? '修改成功！' : '添加成功！')
            // 关闭弹窗
            this.beforeClose()
            this.$emit('close', { update: true })
          }
        }
      })
    },
    closeDialog() {
      this.beforeClose()
      this.$emit('close', { update: false })
    },
    beforeClose() {
      this.$refs.formRef.clearValidate()
      this.$emit('update:show', false)
      this.$emit('reset')
      this.resetForm()
    },
    // 重置表单
    resetForm() {
      this.formData = { ...this.$options.data().formData }
    }
  }
}
</script>

<style scoped></style>
